#!/usr/bin/node

const log = console.log,
    http = require('http'),
    fs = require('fs'),
    url = require('url');

function getPage() {
    let html = fs.readFileSync('./chapters.html');
    html = '<meta charset="UTF-8">' + html;
    return html;
}

const chapterList = require('./data').chapterList;

chapterList.sort((a, b) => {
    return Number(a.publishTimer.split('-').join('')) < Number(b.publishTimer.split('-').join('')) ? 1 : -1
});

http.createServer((req, res) => {
    let addr = url.parse(req.url);

    if (addr.pathname === '/') {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/html');
        res.end(getPage());
    } else if (addr.pathname === '/getlist') {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/json');
        res.end(JSON.stringify(chapterList));
    } else {
        fs.createReadStream(`.${addr.pathname}`).pipe(res);
    }

}).listen(8080);